package com.hengxinguotong.zhihuichengjian.ui;

import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.CarListAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.CarManagementAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Car;
import com.hengxinguotong.zhihuichengjian.bean.CarBean;
import com.hengxinguotong.zhihuichengjian.ptlrecyclerview.PullToLoad.OnLoadListener;
import com.hengxinguotong.zhihuichengjian.ptlrecyclerview.PullToLoad.PullToLoadRecyclerView;
import com.hengxinguotong.zhihuichengjian.ptlrecyclerview.PullToRefresh.OnRefreshListener;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.customdatepicker.CustomDatePicker;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @CopyRight 恒信国通信息科技
 * @Author wulei
 * @Date 2018/8/23
 */

public class CarManagementActivity extends BaseActivity implements View.OnClickListener
{
    private static final String TAG = "CarManagementActivity";
//    @BindView(R.id.data_rv)
//    PullToLoadRecyclerView dataRv;
    @BindView(R.id.data_lv)
    PullToRefreshListView dataLv;
    @BindView(R.id.start_time)
    HXTextView startTime;
    @BindView(R.id.end_time)
    HXTextView endTime;
    @BindView(R.id.car_no)
    HXEditTextView carNo;

    private TimePickerView startPvTime, endPvTime;

    //    private CarManagementAdapter adapter;
    private CarListAdapter carListAdapter;
    private List<Car> carList;
    private Handler handler = new Handler();
    private int pageIndex = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_management);
        ButterKnife.bind(this);
        initView();
        initTimePicker();
        initData();
    }

    private void initView(){
        carList = new ArrayList<>();
//        adapter = new CarManagementAdapter(this, carList);
//        dataRv.setAdapter(adapter);
//        dataRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
//        dataRv.setItemAnimator(new DefaultItemAnimator());
//        dataRv.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onStartRefreshing() {
//                initData();
//            }
//        });
//        dataRv.setOnLoadListener(new OnLoadListener() {
//            @Override
//            public void onStartLoading(int skip) {
//                loadMore();
//            }
//        });

        carListAdapter = new CarListAdapter(carList, this);
        dataLv.setAdapter(carListAdapter);
        dataLv.setMode(PullToRefreshListView.Mode.BOTH);
        dataLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex = 1;
                getCarList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getCarList();
            }
        });
    }

    public void initData(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                pageIndex = 1;
//                getCarList();
                dataLv.setRefreshing();
            }
        }, 500);
    }

    public void loadMore(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getCarList();
            }
        }, 500);
    }

    private void getCarList(){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("startTime", startTime.getText().toString());
            jsonObject.put("endTime", endTime.getText().toString());
            jsonObject.put("pageNum", pageIndex + "");
            jsonObject.put("plateNo", carNo.getEditableText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, this, "/carPass/list/" + SPUtil.getString(this,"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (dataLv.isRefreshing()) {
                    dataLv.onRefreshComplete();
                }
                if(!Utils.isEmpty(json)){
                    Gson gson = new Gson();
                    CarBean carBean = gson.fromJson(json, CarBean.class);
                    if(carBean.getStatus() == 1){
//                        processCars(carBean.getValue());
                        process(carBean.getValue());
//                        carList = carBean.getValue();
//                        if(carList != null && carList.size() > 0){
//                            adapter.setDataList(carList);
//                        }else{
//                            showToast("空数据");
//                        }
                    }else{
                        showToast(carBean.getMsg());
                    }
                }else{
                    showToast("系统异常");
                }

            }

            @Override
            public void onFailure(String json) {
                if (dataLv.isRefreshing()) {
                    dataLv.onRefreshComplete();
                }
                Log.e(TAG, "CarManagementActivity===>>>" + json);
            }
        });
    }

    private void process(List<Car> datas){
        if (pageIndex == 1) {
            if(datas.size()==0){
//                showToast("空数据");
                showEmptyView(dataLv);
            }else{
                dismissEmptyView();
            }
            carList = datas;
            if (datas.size() == Utils.ONCECOUNT) {
                dataLv.setMode(PullToRefreshBase.Mode.BOTH);
            }
        } else {
            carList.addAll(datas);
        }
        carListAdapter.setCarList(carList);

        if (datas.size() < Utils.ONCECOUNT) {
            dataLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        }

        if (datas.size() != 0) {
            pageIndex++;
        }
    }

//    private void processCars(List<Car> datas){
//        if(pageIndex == 1){
//            if(datas.size() == 0){
//                showToast("空数据");
//            }
//            carList.clear();
//            carList.addAll(datas);
//            dataRv.completeRefresh();
//        }else{
//            carList.addAll(datas);
//            dataRv.completeLoad(datas.size());
//        }
//        adapter.setDataList(carList);
//
//        if(datas.size() < Utils.ONCECOUNT){
//            dataRv.setNoMore(true);
//        }else{
//            dataRv.setNoMore(false);
//        }
//
//        if (datas.size() != 0) {
//            pageIndex ++;
//        }
//    }

    @OnClick({R.id.iv_back, R.id.start_time, R.id.end_time, R.id.search_bt})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.start_time:
                startPvTime.show();
                break;
            case R.id.end_time:
                endPvTime.show();
                break;
            case R.id.search_bt:
                initData();
                break;
        }
    }

    private void initTimePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        Date today = new Date();
        String now = sdf.format(today);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(today);
        calendar.add(calendar.DATE, -30);
        String startDate = sdf.format(calendar.getTime());
        startTime.setText(startDate + " 00:00:00");
        endTime.setText(now + " 23:59:59");

        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        selectedDate.setTime(new Date());
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(1970, 0, 1);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.set(2100, 0, 1);

        startPvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                startTime.setText(getTime(date));
            }
        }).setType(new boolean[]{true, true, true, true, true, false})//年月日时分秒 的显示与否，不设置则默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false)
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.BLUE)//设置选中项的颜色
                .setTextColorOut(Color.GRAY)//设置没有被选中项的颜色
                .setContentSize(16)
                .setDate(selectedDate)
                .setLineSpacingMultiplier(2.0f)
                .setTextXOffset(-10, -10, -10, -10, -10, -10)//设置X轴倾斜角度[ -90 , 90°]
                .setRangDate(startCalendar, endCalendar)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();

        endPvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                endTime.setText(getTime(date));
            }
        }).setType(new boolean[]{true, true, true, true, true, false})//年月日时分秒 的显示与否，不设置则默认全部显示
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false)
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.BLUE)//设置选中项的颜色
                .setTextColorOut(Color.GRAY)//设置没有被选中项的颜色
                .setContentSize(16)
                .setDate(selectedDate)
                .setLineSpacingMultiplier(2.0f)
                .setTextXOffset(-5, -5, -5, -5, -5, -5)//设置X轴倾斜角度[ -90 , 90°]
                .setRangDate(startCalendar, endCalendar)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();
    }

    private String getTime(Date date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }


}
